package com.yvon.service.demo.jdk.future;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * @author : Yvon
 * @since : 2021-10-20
 */
@Slf4j
public class GuavaFutureTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Thread.currentThread().setName("主线程");
        ExecutorService executor = Executors.newFixedThreadPool(10);
        UserService userService = new UserService();

        /**
         * 异步操作
         * 【洗茶杯】 【烧水】 【买茶叶】并行执行
         * 执行完毕后获取结果【开始喝茶】
         *
         */
        CompletableFuture<String> hotWaterJobFuture = CompletableFuture.supplyAsync(userService::hotWater);
        CompletableFuture<String> cleanCapsFuture = CompletableFuture.supplyAsync(userService::cleanCaps);
        CompletableFuture<String> buyTeaLeafFuture = CompletableFuture.supplyAsync(userService::buyTeaLeaf);

        CompletableFuture.allOf(hotWaterJobFuture, cleanCapsFuture, buyTeaLeafFuture);
        System.out.println(hotWaterJobFuture.join() + "," + cleanCapsFuture.join() + "," + buyTeaLeafFuture.join());
        System.out.println("开始喝茶");


        /**
         * 集合异步处理
         * 并行分别对1,2,4,6,4进行取名字，获取价格，
         */
        List<Integer> list = Lists.newArrayList(1,2,4,6,4);
        List<CompletableFuture<Integer>> collect = list.stream().map(id -> CompletableFuture.supplyAsync(() -> {
                    String name = userService.getName(id);
                    return userService.getRate(name);
                }, executor)
        ).collect(Collectors.toList());
        List<Integer> collect1 = collect.stream().map(CompletableFuture::join)
                .collect(Collectors.toList());

        System.out.println(collect1);


        System.out.println(collect1);

    }
}
